<template>
  <view class="return-goods">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="title">申请退货</view>
      <view class="subtitle">请选择要退货的商品</view>
    </view>

    <!-- 订单信息 -->
    <view class="order-info" v-if="orderDetail">
      <view class="order-header">
        <view class="order-id">订单号：{{ orderDetail.id }}</view>
        <view class="order-status">{{
          getStatusText(orderDetail.status)
        }}</view>
      </view>
      <view class="order-price">订单金额：￥{{ orderDetail.orderPrice }}</view>
    </view>

    <!-- 商品列表 -->
    <view class="goods-list">
      <view class="section-title">选择退货商品</view>
      <view class="select-all">
        <checkbox-group @change="onSelectAllChange">
          <checkbox :checked="isAllSelected" />
          <text class="select-all-text">全选</text>
        </checkbox-group>
      </view>

      <view
        class="goods-item"
        v-for="(item, index) in orderDetail.orderItems"
        :key="item.id"
      >
        <view class="goods-checkbox">
          <checkbox-group @change="onItemSelect" :data-index="index">
            <checkbox :value="item.id" :checked="isItemSelected(item.id)" />
          </checkbox-group>
        </view>

        <view class="goods-content">
          <view class="goods-image">
            <image :src="getProductImage(item)" mode="aspectFill"></image>
          </view>

          <view class="goods-details">
            <view class="goods-name">{{ getProductName(item) }}</view>
            <view class="goods-spec" v-if="item.product.pSpecifications">
              规格：{{ item.product.pSpecifications }}
            </view>
            <view class="goods-price-info">
              <view class="price">￥{{ item.pPrice }}</view>
              <view class="quantity">x{{ item.pNumber }}</view>
            </view>

            <!-- 数量选择器 -->
            <view class="quantity-selector" v-if="isItemSelected(item.id)">
              <view class="quantity-label">退货数量：</view>
              <view class="quantity-controls">
                <button
                  class="quantity-btn minus"
                  @click="decreaseQuantity(item.id)"
                  :disabled="getReturnQuantity(item.id) <= 1"
                >
                  -
                </button>
                <input
                  class="quantity-input"
                  type="number"
                  :value="getReturnQuantity(item.id)"
                  @input="onQuantityInput(item.id, $event)"
                  :max="item.pNumber"
                  min="1"
                />
                <button
                  class="quantity-btn plus"
                  @click="increaseQuantity(item.id)"
                  :disabled="
                    getReturnQuantity(item.id) >= parseInt(item.pNumber)
                  "
                >
                  +
                </button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 退货原因 -->
    <view class="return-reason">
      <view class="section-title">退货原因</view>
      <textarea
        v-model="returnReason"
        placeholder="请详细说明退货原因..."
        maxlength="200"
        class="reason-input"
      ></textarea>
      <view class="char-count">{{ returnReason.length }}/200</view>
    </view>

    <!-- 底部操作按钮 -->
    <view class="bottom-actions">
      <view class="selected-info">
        已选择 {{ getSelectedItemsCount() }} 件商品
      </view>
      <view class="action-buttons">
        <button class="cancel-btn" @click="goBack">取消</button>
        <button
          class="submit-btn"
          @click="submitReturn"
          :disabled="getSelectedItemsCount() === 0 || !returnReason.trim()"
        >
          提交申请
        </button>
      </view>
    </view>

    <!-- 加载中 -->
    <view class="loading" v-if="loading">
      <text>加载中...</text>
    </view>
  </view>
</template>

<script>
import { getOrderDetail, applyRefund } from "../../../common/api/orderList.js";
import { getFirstImage } from "@/common/utils/index.js";
import { add, safeNumber } from "@/common/utils/precision.js";

export default {
  data() {
    return {
      orderId: "",
      orderDetail: null,
      selectedItems: {}, // 选中的商品ID和数量，格式: { itemId: quantity }
      returnReason: "",
      loading: false,
      submitting: false,
    };
  },
  computed: {
    isAllSelected() {
      if (!this.orderDetail || !this.orderDetail.orderItems) return false;
      return (
        Object.keys(this.selectedItems).length ===
        this.orderDetail.orderItems.length
      );
    },
  },
  onLoad(options) {
    this.orderId = options.orderId;
    if (this.orderId) {
      this.loadOrderDetail();
    } else {
      uni.showToast({
        title: "订单ID不能为空",
        icon: "none",
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    }
  },
  methods: {
    // 加载订单详情
    async loadOrderDetail() {
      try {
        this.loading = true;
        const response = await getOrderDetail(this.orderId);

        if (response.data && response.data.ok) {
          this.orderDetail = response.data.data;
          // 验证订单状态
          if (this.orderDetail.status !== "SHIPPED") {
            uni.showModal({
              title: "提示",
              content: "只有待收货状态的订单才能申请退货",
              showCancel: false,
              success: () => {
                uni.navigateBack();
              },
            });
            return;
          }
        } else {
          throw new Error(response.data?.message || "获取订单详情失败");
        }
      } catch (error) {
        console.error("加载订单详情失败:", error);
        uni.showToast({
          title: "加载订单详情失败",
          icon: "none",
        });
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      } finally {
        this.loading = false;
      }
    },

    // 全选/取消全选
    onSelectAllChange(e) {
      if (e.detail.value.length > 0) {
        // 全选，每个商品默认退货数量为1
        const newSelectedItems = {};
        this.orderDetail.orderItems.forEach((item) => {
          newSelectedItems[item.id] = 1;
        });
        this.selectedItems = newSelectedItems;
      } else {
        // 取消全选
        this.selectedItems = {};
      }
    },

    // 单个商品选择
    onItemSelect(e) {
      const checkedValues = e.detail.value;
      const targetElement = e.target || e.currentTarget;
      const index = targetElement.dataset?.index;

      // 获取当前商品项
      const currentItem = this.orderDetail.orderItems[index];
      if (!currentItem) return;

      const itemId = currentItem.id;
      const newSelectedItems = { ...this.selectedItems };

      // 检查当前商品是否在选中列表中
      if (checkedValues.includes(itemId)) {
        // 如果被选中且之前没有选择过，添加到选中列表，默认数量为1
        if (!newSelectedItems[itemId]) {
          newSelectedItems[itemId] = 1;
        }
      } else {
        // 如果没有被选中，从选中列表中移除
        delete newSelectedItems[itemId];
      }

      this.selectedItems = newSelectedItems;
    },

    // 检查商品是否被选中
    isItemSelected(itemId) {
      return this.selectedItems.hasOwnProperty(itemId);
    },

    // 获取商品的退货数量
    getReturnQuantity(itemId) {
      return this.selectedItems[itemId] || 1;
    },

    // 增加数量 - 使用精度工具
    increaseQuantity(itemId) {
      const item = this.orderDetail.orderItems.find(
        (item) => item.id === itemId
      );
      const maxQuantity = safeNumber(item.pNumber, 1);
      const currentQuantity = safeNumber(this.selectedItems[itemId], 1);

      if (currentQuantity < maxQuantity) {
        this.$set(this.selectedItems, itemId, add(currentQuantity, 1, 0));
      }
    },

    // 减少数量 - 使用精度工具
    decreaseQuantity(itemId) {
      const currentQuantity = safeNumber(this.selectedItems[itemId], 1);
      if (currentQuantity > 1) {
        this.$set(this.selectedItems, itemId, Math.max(1, currentQuantity - 1));
      }
    },

    // 数量输入事件 - 使用精度工具
    onQuantityInput(itemId, e) {
      const value = safeNumber(e.target.value, 1);
      const item = this.orderDetail.orderItems.find(
        (item) => item.id === itemId
      );
      const maxQuantity = safeNumber(item.pNumber, 1);

      // 限制数量范围
      const quantity = Math.max(1, Math.min(value, maxQuantity));
      this.$set(this.selectedItems, itemId, quantity);
    },

    // 获取选中商品总数 - 使用精度工具
    getSelectedItemsCount() {
      return Object.values(this.selectedItems).reduce(
        (total, quantity) => add(total, safeNumber(quantity, 0), 0),
        0
      );
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        PENDING_SHIP: "待发货",
        SHIPPED: "待收货",
        PENDING_PAYMENT: "待付款",
        COMPLETED: "已完成",
        RETURN_REQUESTED: "退货申请中",
        RETURN_APPROVED: "退货已同意",
        RETURN_REJECTED: "退货被拒绝",
        RETURNED: "已退货",
        CANCELLED: "已取消",
      };
      return statusMap[status] || "未知状态";
    },

    // 获取商品名称
    getProductName(item) {
      return item.product?.pName || "未知商品";
    },

    // 获取商品图片
    getProductImage(item) {
      return getFirstImage(item.product?.pImgUrl) || "/static/img/noorder.png";
    },

    // 返回
    goBack() {
      uni.navigateBack();
    },

    // 提交退货申请
    async submitReturn() {
      if (Object.keys(this.selectedItems).length === 0) {
        uni.showToast({
          title: "请选择要退货的商品",
          icon: "none",
        });
        return;
      }

      if (!this.returnReason.trim()) {
        uni.showToast({
          title: "请输入退货原因",
          icon: "none",
        });
        return;
      }

      if (this.submitting) return;

      try {
        this.submitting = true;
        uni.showLoading({
          title: "提交申请中...",
        });

        // 构建退货商品列表
        const returnItems = Object.keys(this.selectedItems).map((itemId) => ({
          orderItemId: itemId,
          returnQuantity: this.selectedItems[itemId],
        }));

        // 判断是否为全部商品且数量都相等（即整单退货）
        const isFullOrder =
          this.orderDetail.orderItems.every((item) => {
            const returnQuantity = this.selectedItems[item.id];
            return returnQuantity && returnQuantity === parseInt(item.pNumber);
          }) &&
          Object.keys(this.selectedItems).length ===
            this.orderDetail.orderItems.length;

        // 如果是整单退货，传递null；否则传递具体的退货商品列表
        const submitData = isFullOrder ? null : returnItems;

        await applyRefund(this.orderId, this.returnReason.trim(), submitData);

        uni.showToast({
          title: "退货申请已提交",
          icon: "success",
        });

        // 延迟返回到订单列表
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      } catch (error) {
        console.error("提交退货申请失败:", error);
        uni.showToast({
          title: "提交失败，请重试",
          icon: "none",
        });
      } finally {
        this.submitting = false;
        uni.hideLoading();
      }
    },
  },
};
</script>

<style lang="scss">
.return-goods {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120upx;
}

.header {
  background-color: #fff;
  padding: 30upx 40upx;
  border-bottom: 1upx solid #f0f0f0;

  .title {
    font-size: 36upx;
    font-weight: 600;
    color: #333;
    margin-bottom: 10upx;
  }

  .subtitle {
    font-size: 28upx;
    color: #666;
  }
}

.order-info {
  background-color: #fff;
  margin: 20upx 30upx;
  padding: 30upx;
  border-radius: 16upx;

  .order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20upx;

    .order-id {
      font-size: 28upx;
      color: #333;
    }

    .order-status {
      font-size: 26upx;
      color: #ff6b35;
      padding: 6upx 16upx;
      background-color: #fff3f0;
      border-radius: 20upx;
    }
  }

  .order-price {
    font-size: 32upx;
    color: #ff6b35;
    font-weight: 600;
  }
}

.goods-list {
  background-color: #fff;
  margin: 20upx 30upx;
  border-radius: 16upx;
  overflow: hidden;

  .section-title {
    padding: 30upx 30upx 20upx;
    font-size: 32upx;
    font-weight: 600;
    color: #333;
    border-bottom: 1upx solid #f0f0f0;
  }

  .select-all {
    padding: 20upx 30upx;
    display: flex;
    align-items: center;
    border-bottom: 1upx solid #f0f0f0;

    .select-all-text {
      margin-left: 20upx;
      font-size: 28upx;
      color: #333;
    }
  }

  .goods-item {
    display: flex;
    align-items: center;
    padding: 30upx;
    border-bottom: 1upx solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .goods-checkbox {
      margin-right: 20upx;
    }

    .goods-content {
      flex: 1;
      display: flex;
      align-items: center;

      .goods-image {
        width: 120upx;
        height: 120upx;
        margin-right: 20upx;
        border-radius: 12upx;
        overflow: hidden;

        image {
          width: 100%;
          height: 100%;
        }
      }

      .goods-details {
        flex: 1;

        .goods-name {
          font-size: 30upx;
          color: #333;
          margin-bottom: 10upx;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          overflow: hidden;
        }

        .goods-spec {
          font-size: 24upx;
          color: #999;
          margin-bottom: 10upx;
        }

        .goods-price-info {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .price {
            font-size: 32upx;
            color: #ff6b35;
            font-weight: 600;
          }

          .quantity {
            font-size: 28upx;
            color: #666;
          }
        }

        .quantity-selector {
          margin-top: 20upx;
          padding: 20upx;
          background-color: #f8f8f8;
          border-radius: 12upx;

          .quantity-label {
            font-size: 28upx;
            color: #333;
            margin-bottom: 16upx;
            font-weight: 500;
          }

          .quantity-controls {
            display: flex;
            align-items: center;
            justify-content: flex-start;
            gap: 20upx;

            .quantity-btn {
              width: 60upx;
              height: 60upx;
              border: 1upx solid #ddd;
              border-radius: 8upx;
              background-color: #fff;
              color: #333;
              font-size: 32upx;
              font-weight: 600;
              display: flex;
              align-items: center;
              justify-content: center;

              &.minus:disabled,
              &.plus:disabled {
                background-color: #f5f5f5;
                color: #ccc;
                border-color: #eee;
              }

              &:not(:disabled):active {
                background-color: #f0f0f0;
              }
            }

            .quantity-input {
              width: 120upx;
              height: 60upx;
              border: 1upx solid #ddd;
              border-radius: 8upx;
              text-align: center;
              font-size: 28upx;
              background-color: #fff;
            }
          }
        }
      }
    }
  }
}

.return-reason {
  background-color: #fff;
  margin: 20upx 30upx;
  border-radius: 16upx;
  padding: 30upx;

  .section-title {
    font-size: 32upx;
    font-weight: 600;
    color: #333;
    margin-bottom: 20upx;
  }

  .reason-input {
    width: 100%;
    min-height: 200upx;
    padding: 20upx;
    border: 1upx solid #e0e0e0;
    border-radius: 12upx;
    font-size: 28upx;
    color: #333;
    resize: none;
  }

  .char-count {
    text-align: right;
    margin-top: 10upx;
    font-size: 24upx;
    color: #999;
  }
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20upx 30upx;
  border-top: 1upx solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .selected-info {
    font-size: 28upx;
    color: #666;
  }

  .action-buttons {
    display: flex;
    gap: 20upx;

    .cancel-btn {
      padding: 16upx 40upx;
      border: 1upx solid #ddd;
      border-radius: 50upx;
      background-color: #fff;
      color: #333;
      font-size: 28upx;
    }

    .submit-btn {
      padding: 16upx 40upx;
      border: none;
      border-radius: 50upx;
      background-color: #ff6b35;
      color: #fff;
      font-size: 28upx;

      &:disabled {
        background-color: #ccc;
        color: #666;
      }
    }
  }
}

.loading {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.7);
  color: #fff;
  padding: 40upx;
  border-radius: 16upx;
  font-size: 28upx;
}
</style>
